package com.hframe;

import com.hframe.data.DRef;
import com.hframe.utils.FileUtil;
import com.hframe.xml.XmlToData;
import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import javax.servlet.ServletContext;

public class ReadConfig {

    private static Logger log = Logger.getLogger(ReadConfig.class);
    protected String configFile = "Config.xml";

    public ReadConfig(ServletContext context) {
        this.configFile = context.getRealPath("/WEB-INF/") + configFile;
    }

    protected boolean readConfig(DRef<? extends DRef<?>> config) {
        return readConfig(config, configFile);
    }

    protected boolean readConfig(DRef<? extends DRef<?>> config, String filePath) {
        return readXmlConfig(config, FileUtil.readString(filePath));
    }

    protected boolean readXmlConfig(DRef<? extends DRef<?>> config, String xml) {
        if (0 != xml.length())
            try {
                return readXmlConfig(config, DocumentHelper.parseText(xml).getRootElement());
            } catch (DocumentException e) {
                log.error(e, e);
            }
        return false;
    }

    protected boolean readXmlConfig(DRef<? extends DRef<?>> config, Element element) {
        return XmlToData.convert(element, config);
    }


}
